//
//  SPGameViewModel.m
//  shandong_porker
//
//  Created by Developer on 2025-01-08.
//  Copyright © 2025 ShandongPoker. All rights reserved.
//

#import "SPGameViewModel.h"
#import "../../Models/Game/SPPlayer.h"
#import "../../Models/Game/SPCard.h"
#import "../../Core/Utils/SPConstants.h"

@interface SPGameViewModel ()

// 私有属性
@property (nonatomic, assign, readwrite) SPGameState gameState;
@property (nonatomic, assign, readwrite) NSInteger currentPot;
@property (nonatomic, assign, readwrite) NSInteger currentRound;
@property (nonatomic, assign, readwrite) BOOL isPaused;

@property (nonatomic, strong, readwrite) NSMutableArray<SPPlayer *> *mutablePlayers;
@property (nonatomic, strong, readwrite) SPPlayer *currentPlayer;
@property (nonatomic, strong, readwrite) SPPlayer *activePlayer;

@property (nonatomic, strong, readwrite) NSMutableArray<SPCard *> *mutableCommunityCards;
@property (nonatomic, strong, readwrite) NSMutableArray<SPCard *> *mutablePlayerHoleCards;

// 游戏逻辑属性
@property (nonatomic, strong) NSMutableArray<SPCard *> *deck;
@property (nonatomic, assign) NSInteger currentPlayerIndex;
@property (nonatomic, assign) NSInteger dealerIndex;

@end

@implementation SPGameViewModel

#pragma mark - Initialization

- (instancetype)init {
    if (self = [super init]) {
        [self initializeGame];
    }
    return self;
}

- (void)initializeGame {
    self.gameState = SPGameStateIdle;
    self.currentPot = 0;
    self.currentRound = 0;
    self.isPaused = NO;
    
    self.mutablePlayers = [[NSMutableArray alloc] init];
    self.mutableCommunityCards = [[NSMutableArray alloc] init];
    self.mutablePlayerHoleCards = [[NSMutableArray alloc] init];
    
    self.currentPlayerIndex = 0;
    self.dealerIndex = 0;
}

#pragma mark - Public Properties

- (NSArray<SPPlayer *> *)players {
    return [self.mutablePlayers copy];
}

- (NSArray<SPCard *> *)communityCards {
    return [self.mutableCommunityCards copy];
}

- (NSArray<SPCard *> *)playerHoleCards {
    return [self.mutablePlayerHoleCards copy];
}

#pragma mark - Game Control Methods

- (void)startNewGameWithPlayers:(NSArray<NSString *> *)playerNames 
                   aiDifficulty:(SPAIDifficulty)aiDifficulty {
    
    [self setLoading:YES];
    
    // 清理之前的游戏状态
    [self resetGame];
    
    // 创建玩家
    [self createPlayersWithNames:playerNames aiDifficulty:aiDifficulty];
    
    // 初始化牌组
    [self initializeDeck];
    
    // 开始游戏
    [self beginNewRound];
    
    [self setLoading:NO];
}

- (void)pauseGame {
    self.isPaused = YES;
    [self notifyGameStateChange];
}

- (void)resumeGame {
    self.isPaused = NO;
    [self notifyGameStateChange];
}

- (void)endGame {
    self.gameState = SPGameStateEnded;
    [self notifyGameStateChange];
    
    // 找出获胜者
    SPPlayer *winner = [self determineWinner];
    NSInteger winAmount = self.currentPot;
    
    if (self.gameDidEnd) {
        self.gameDidEnd(winner, winAmount);
    }
}

#pragma mark - Player Actions

- (void)playerFold {
    if (![self canPlayerPerformAction:SPPlayerActionFold]) return;
    
    self.currentPlayer.hasFolded = YES;
    [self notifyPlayerAction:SPPlayerActionFold amount:0];
    [self nextPlayer];
}

- (void)playerCheck {
    if (![self canPlayerPerformAction:SPPlayerActionCheck]) return;
    
    [self notifyPlayerAction:SPPlayerActionCheck amount:0];
    [self nextPlayer];
}

- (void)playerCall {
    if (![self canPlayerPerformAction:SPPlayerActionCall]) return;
    
    NSInteger callAmount = [self getCurrentCallAmount];
    [self.currentPlayer call:callAmount];
    self.currentPot += callAmount;
    
    [self notifyPlayerAction:SPPlayerActionCall amount:callAmount];
    [self notifyPotChange];
    [self nextPlayer];
}

- (void)playerRaise:(NSInteger)amount {
    if (![self canPlayerPerformAction:SPPlayerActionRaise]) return;
    
    if (amount < [self getMinRaiseAmount] || amount > [self getMaxRaiseAmount]) {
        NSError *error = [NSError errorWithDomain:SPGameErrorDomain 
                                             code:1001 
                                         userInfo:@{NSLocalizedDescriptionKey: @"加注金额无效"}];
        [self setError:error];
        return;
    }
    
    [self.currentPlayer raise:amount];
    self.currentPot += amount;
    
    [self notifyPlayerAction:SPPlayerActionRaise amount:amount];
    [self notifyPotChange];
    [self nextPlayer];
}

- (void)playerAllIn {
    if (![self canPlayerPerformAction:SPPlayerActionAllIn]) return;
    
    NSInteger allInAmount = [self.currentPlayer allIn];
    self.currentPot += allInAmount;
    
    [self notifyPlayerAction:SPPlayerActionAllIn amount:allInAmount];
    [self notifyPotChange];
    [self nextPlayer];
}

#pragma mark - Query Methods

- (NSInteger)getCurrentCallAmount {
    // 简化实现：返回固定值
    return 100;
}

- (NSInteger)getMinRaiseAmount {
    return [self getCurrentCallAmount] * 2;
}

- (NSInteger)getMaxRaiseAmount {
    return self.currentPlayer.chips;
}

- (BOOL)canPlayerPerformAction:(SPPlayerAction)action {
    if (self.isPaused || self.gameState == SPGameStateEnded) {
        return NO;
    }
    
    if (!self.currentPlayer || self.currentPlayer.hasFolded) {
        return NO;
    }
    
    switch (action) {
        case SPPlayerActionFold:
            return YES;
            
        case SPPlayerActionCheck:
            return [self getCurrentCallAmount] == 0;
            
        case SPPlayerActionCall:
            return [self getCurrentCallAmount] > 0 && 
                   self.currentPlayer.chips >= [self getCurrentCallAmount];
            
        case SPPlayerActionRaise:
            return self.currentPlayer.chips >= [self getMinRaiseAmount];
            
        case SPPlayerActionAllIn:
            return self.currentPlayer.chips > 0;
    }
    
    return NO;
}

#pragma mark - Private Methods

- (void)resetGame {
    [self.mutablePlayers removeAllObjects];
    [self.mutableCommunityCards removeAllObjects];
    [self.mutablePlayerHoleCards removeAllObjects];
    
    self.currentPot = 0;
    self.currentRound = 0;
    self.gameState = SPGameStateIdle;
    self.currentPlayer = nil;
    self.activePlayer = nil;
}

- (void)createPlayersWithNames:(NSArray<NSString *> *)playerNames 
                  aiDifficulty:(SPAIDifficulty)aiDifficulty {
    
    for (NSInteger i = 0; i < playerNames.count; i++) {
        SPPlayer *player;
        if (i == 0) {
            // 第一个是人类玩家
            player = [[SPPlayer alloc] initWithName:playerNames[i] 
                                              chips:SP_DEFAULT_STARTING_CHIPS];
        } else {
            // 其他是AI玩家
            player = [[SPPlayer alloc] initWithName:playerNames[i] 
                                              chips:SP_DEFAULT_STARTING_CHIPS 
                                       aiDifficulty:aiDifficulty];
        }
        
        player.position = i;
        [self.mutablePlayers addObject:player];
    }
    
    // 设置当前玩家为人类玩家
    self.currentPlayer = self.mutablePlayers.firstObject;
    self.activePlayer = self.currentPlayer;
}

- (void)initializeDeck {
    self.deck = [[NSMutableArray alloc] init];
    
    // 创建52张牌
    for (SPCardSuit suit = SPCardSuitSpades; suit <= SPCardSuitClubs; suit++) {
        for (SPCardRank rank = SPCardRankTwo; rank <= SPCardRankAce; rank++) {
            SPCard *card = [[SPCard alloc] initWithSuit:suit rank:rank];
            [self.deck addObject:card];
        }
    }
    
    // 洗牌
    [self shuffleDeck];
}

- (void)shuffleDeck {
    for (NSInteger i = self.deck.count - 1; i > 0; i--) {
        NSInteger j = arc4random_uniform((uint32_t)(i + 1));
        [self.deck exchangeObjectAtIndex:i withObjectAtIndex:j];
    }
}

- (void)beginNewRound {
    self.gameState = SPGameStateDealing;
    [self notifyGameStateChange];
    
    // 重置玩家状态
    for (SPPlayer *player in self.mutablePlayers) {
        [player resetForNewRound];
    }
    
    // 发手牌
    [self dealHoleCards];
    
    // 进入翻牌前阶段
    self.gameState = SPGameStatePreFlop;
    [self notifyGameStateChange];
    
    // 设置当前玩家为人类玩家（第一个玩家）
    self.currentPlayerIndex = 0;
    self.currentPlayer = self.mutablePlayers.firstObject;
    self.activePlayer = self.currentPlayer;
    
    NSLog(@"GameViewModel: 游戏开始，当前玩家: %@", self.currentPlayer.name);
}

- (void)dealHoleCards {
    // 给每个玩家发2张手牌
    for (NSInteger cardIndex = 0; cardIndex < SP_CARDS_PER_PLAYER; cardIndex++) {
        for (SPPlayer *player in self.mutablePlayers) {
            if (self.deck.count > 0) {
                SPCard *card = [self.deck lastObject];
                [self.deck removeLastObject];
                [player addHoleCard:card];
                
                // 如果是人类玩家，更新手牌显示
                if (player == self.currentPlayer) {
                    [self.mutablePlayerHoleCards addObject:card];
                }
            }
        }
    }
    
    // 通知手牌更新
    if (self.playerCardsDidUpdate) {
        self.playerCardsDidUpdate([self.mutablePlayerHoleCards copy]);
    }
}

- (void)nextPlayer {
    NSLog(@"GameViewModel: 下一个玩家");
    
    // 移动到下一个玩家
    self.currentPlayerIndex = (self.currentPlayerIndex + 1) % self.mutablePlayers.count;
    self.currentPlayer = self.mutablePlayers[self.currentPlayerIndex];
    
    // 如果当前玩家已经弃牌，继续下一个
    while (self.currentPlayer.hasFolded && self.currentPlayerIndex != 0) {
        self.currentPlayerIndex = (self.currentPlayerIndex + 1) % self.mutablePlayers.count;
        self.currentPlayer = self.mutablePlayers[self.currentPlayerIndex];
    }
    
    // 如果回到第一个玩家（人类玩家），说明一轮结束，进入下一阶段
    if (self.currentPlayerIndex == 0) {
        [self checkRoundProgression];
        return;
    }
    
    // 如果是AI玩家，让AI自动行动
    if (self.currentPlayer != self.mutablePlayers.firstObject) {
        [self performAIAction];
    }
}

- (void)performAIAction {
    NSLog(@"GameViewModel: AI玩家 %@ 开始行动", self.currentPlayer.name);
    
    // 简单的AI逻辑：随机选择操作
    NSArray *actions = @[@(SPPlayerActionFold), @(SPPlayerActionCall), @(SPPlayerActionRaise)];
    SPPlayerAction action = [actions[arc4random_uniform((uint32_t)actions.count)] integerValue];
    
    // 延迟一下，让玩家能看到AI的行动
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        switch (action) {
            case SPPlayerActionFold:
                [self playerFold];
                break;
            case SPPlayerActionCall:
                [self playerCall];
                break;
            case SPPlayerActionRaise:
                [self playerRaise:200]; // AI固定加注200
                break;
            default:
                [self playerFold];
                break;
        }
    });
}

- (void)checkRoundProgression {
    // 简化实现：自动进入下一阶段
    switch (self.gameState) {
        case SPGameStatePreFlop:
            [self dealFlop];
            break;
        case SPGameStateFlop:
            [self dealTurn];
            break;
        case SPGameStateTurn:
            [self dealRiver];
            break;
        case SPGameStateRiver:
            [self showdown];
            break;
        default:
            break;
    }
}

- (void)dealFlop {
    // 发3张公共牌
    for (NSInteger i = 0; i < 3; i++) {
        if (self.deck.count > 0) {
            SPCard *card = [self.deck lastObject];
            [self.deck removeLastObject];
            [self.mutableCommunityCards addObject:card];
        }
    }
    
    self.gameState = SPGameStateFlop;
    [self notifyGameStateChange];
    [self notifyCommunityCardsUpdate];
}

- (void)dealTurn {
    // 发1张转牌
    if (self.deck.count > 0) {
        SPCard *card = [self.deck lastObject];
        [self.deck removeLastObject];
        [self.mutableCommunityCards addObject:card];
    }
    
    self.gameState = SPGameStateTurn;
    [self notifyGameStateChange];
    [self notifyCommunityCardsUpdate];
}

- (void)dealRiver {
    // 发1张河牌
    if (self.deck.count > 0) {
        SPCard *card = [self.deck lastObject];
        [self.deck removeLastObject];
        [self.mutableCommunityCards addObject:card];
    }
    
    self.gameState = SPGameStateRiver;
    [self notifyGameStateChange];
    [self notifyCommunityCardsUpdate];
}

- (void)showdown {
    self.gameState = SPGameStateShowdown;
    [self notifyGameStateChange];
    
    // 延迟结束游戏
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self endGame];
    });
}

- (SPPlayer *)determineWinner {
    // 简化实现：返回第一个未弃牌的玩家
    for (SPPlayer *player in self.mutablePlayers) {
        if (!player.hasFolded) {
            return player;
        }
    }
    return self.mutablePlayers.firstObject;
}

#pragma mark - Notification Methods

- (void)notifyGameStateChange {
    if (self.gameStateDidChange) {
        self.gameStateDidChange(self.gameState);
    }
}

- (void)notifyPotChange {
    if (self.potDidChange) {
        self.potDidChange(self.currentPot);
    }
}

- (void)notifyCommunityCardsUpdate {
    if (self.communityCardsDidUpdate) {
        self.communityCardsDidUpdate([self.mutableCommunityCards copy]);
    }
}

- (void)notifyPlayerAction:(SPPlayerAction)action amount:(NSInteger)amount {
    if (self.playerDidAct) {
        self.playerDidAct(self.currentPlayer, action, amount);
    }
}

@end